<template>
    <div>
        <Button type="primary" ghost icon="md-add" @click="handleOpenCreate">添加用户</Button>
        <Button @click="handleDeleteMultiple" type="error" ghost icon="md-trash" class="ivu-ml-8"
                v-show="selectedData.length">批量删除
        </Button>
        <div class="ivu-inline-block ivu-fr">
            <Dropdown @on-click="handleChangeTableSize" trigger="click">
                <Tooltip class="ivu-ml" content="密度" placement="top">
                    <i-link>
                        <Icon type="md-list"/>
                    </i-link>
                </Tooltip>
                <DropdownMenu slot="list">
                    <DropdownItem name="default" :selected="tableSize === 'default'">默认</DropdownItem>
                    <DropdownItem name="large" :selected="tableSize === 'large'">宽松</DropdownItem>
                    <DropdownItem name="small" :selected="tableSize === 'small'">紧凑</DropdownItem>
                </DropdownMenu>
            </Dropdown>
            <Tooltip class="ivu-ml" :content="tableFullscreen ? '退出全屏' : '全屏'" placement="top">
                <i-link @click.native="handleFullscreen">
                    <Icon :custom="tableFullscreen ? 'i-icon i-icon-exit-full-screen' : 'i-icon i-icon-full-screen'"/>
                </i-link>
            </Tooltip>
            <Tooltip class="ivu-ml" content="刷新" placement="top">
                <i-link @click.native="handleRefresh">
                    <Icon custom="i-icon i-icon-refresh"/>
                </i-link>
            </Tooltip>
            <Dropdown trigger="click">
                <Tooltip class="ivu-ml" content="列设置" placement="top">
                    <i-link>
                        <Icon type="md-options"/>
                    </i-link>
                </Tooltip>
                <DropdownMenu slot="list">
                    <div class="ivu-p-8">列展示</div>
                    <Divider size="small" class="ivu-mt-8 ivu-mb-8"/>
                    <template v-for="item in columns">
                        <li class="ivu-dropdown-item" :key="item.title" v-if="item.title"
                            @click="item.show = !item.show">
                            <Checkbox v-model="item.show"></Checkbox>
                            <span>{{ item.title }}</span>
                        </li>
                    </template>
                </DropdownMenu>
            </Dropdown>
        </div>
        <Table
            ref="table"
            :columns="tableColumns"
            :data="list"
            :loading="loading"
            :size="tableSize"
            class="ivu-mt"
            @on-row-click="handleClickRow"
            @on-sort-change="handleSortChange"
            @on-select="handleSelect"
            @on-select-cancel="handleSelectCancel"
            @on-select-all="handleSelectAll"
            @on-select-all-cancel="handleClearSelect">
            <template slot-scope="{ row }" slot="status">
                <Badge v-if="row.useStateCode === '1'" color="green" text="正常"/>
                <Badge v-if="row.useStateCode === '2'" color="yellow" text="冻结"/>
                <Badge v-if="row.useStateCode === '3'" color="red" text="关闭"/>
            </template>
            <template slot-scope="{ row }" slot="gender">
                <Tag v-if="row.genderCode === '1'" color="blue">男</Tag>
                <Tag v-if="row.genderCode === '2'" color="magenta">女</Tag>
            </template>
            <template slot-scope="{ row }" slot="position">
                {{ getPositionNameBy(row.positionId) }}
            </template>
            <template slot-scope="{ row }" slot="dept">
                {{ getDeptNameBy(row.deptId) }}
            </template>
            <template slot-scope="{ row }" slot="action">
                <div v-if="row.account != 'admin'" @click.stop.prevent>
                    <a type="text" @click="handleOpenPermission(row.id)">授权</a>
                    <Divider type="vertical"/>
                    <a type="text" @click="handleEdit(row.id)">编辑</a>
                    <Divider type="vertical"/>
                    <a type="text" @click="handleDelete(row.id)">删除</a>
                </div>
            </template>
        </Table>
        <div class="ivu-mt ivu-text-center">
            <Page
                :total="pageNation.total"
                :page-size-opts="pageSizeOpts"
                :current.sync="pageNation.pageNumber"
                show-total
                show-sizer
                show-elevator
                :page-size="pageNation.pageSize"
                @on-change="handleChangePage"
                @on-page-size-change="handleChangePageSize"
            />
        </div>
        <Drawer
            :styles="drawer.styles"
            v-model="drawer.show"
            :title="drawer.type === 'edit' ? '编辑用户' : drawer.type === 'new' ? '添加用户' : '用户信息'"
            width="560"
            :before-close="handleCloseEdit"
            :transfer="false">
            <Form
                v-if="userInfo && userInfoFormReady"
                ref="userInfoForm"
                class="page-sys-user-drawer-form"
                :model="userInfo"
                :rules="userInfoRules"
                :disabled="drawer.type === 'read'"
                label-position="top"
                hide-required-mark>
                <Row :gutter="32">
                    <Col span="8">
                        <FormItem prop="userName" label="用户名">
                            <Input v-model="userInfo.userName" clearable placeholder="请选择用户名，必填"
                                   @on-clear="onInputClear" readonly/>
                        </FormItem>
                    </Col>
                    <Col span="4">
                        <FormItem label=" ">
                            <Button type="primary" @click="handleUserSelect">选择</Button>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem prop="mobilePhone" label="手机号">
                            <Input v-model="userInfo.mobilePhone" placeholder="请输入手机号，必填" maxlength="11"/>
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="12">
                        <FormItem prop="email" label="邮箱">
                            <Input v-model="userInfo.email" placeholder="请输入邮箱"/>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem prop="genderCode" label="性别">
                            <Select v-model="userInfo.genderCode" placeholder="请选择性别">
                                <Option value="1">男</Option>
                                <Option value="2">女</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="12">
                        <FormItem prop="useStateCode" label="状态">
                            <Select v-model="userInfo.useStateCode" placeholder="请选择状态">
                                <Option value="1">正常</Option>
                                <Option value="2">冻结</Option>
                                <Option value="3">关闭</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem prop="account" label="登录账号">
                            <Input v-model="userInfo.account" placeholder="请输入登录账号，必填"/>
                        </FormItem>
                    </Col>
                </Row>
                <Divider/>
                <FormItem prop="userDescrib" label="个人介绍">
                    <Input v-model="userInfo.userDescrib" placeholder="请输入个人介绍" type="textarea"
                           :autosize="{ minRows: 3 }"/>
                </FormItem>
            </Form>
            <div class="page-sys-user-drawer-footer" v-if="drawer.type === 'edit'">
                <Button class="ivu-ml" type="error" @click="handleResetPassword()">重置密码</Button> &nbsp;&nbsp;&nbsp;&nbsp;
                <Button type="primary" @click="handleSubmitEdit" :loading="submitting">提交</Button>
            </div>
            <div class="page-sys-user-drawer-footer" v-if="drawer.type === 'new'">
                <Button type="primary" @click="handleSubmitNew" :loading="submitting">提交</Button>
            </div>
        </Drawer>
        <Modal v-model="modal.show" :title="userInfo ? '分配 ' + userInfo.userName + ' 的用户权限' : ''" :transfer="false"
               :styles="{top: modalTop+'px',width:'800px'}">
            <template >
                <Tabs size="small">
                    <TabPane label="角色管理">
                        <tableRoleList ref="tableRole" :selectedRoleIds="selectedRoleIds"></tableRoleList>
                    </TabPane>
                    <TabPane label="角色组管理">
                        <tableRolegpList ref="tableRolegp" :selectedRolegpIds="selectedRolegpIds"></tableRolegpList>
                    </TabPane>
                </Tabs>
                <div slot="footer">
                    <Button type="primary" :loading="submitting" @click="handleSubmitPermission">提交</Button>
                </div>
            </template>
        </Modal>
        <Modal v-model="userModalShow" title="关联用户列表" :transfer="false" :styles="{top:'200px',width:'800px'}">
            <template>
                <div>
                    <tableUserList ref="tableUser" @handleSubmit="handleSelectSubmit"></tableUserList>
                </div>
                <div slot="footer">
                    <Button type="primary" :loading="submitting" @click="handleUserModalClose">关闭</Button>
                </div>
            </template>
        </Modal>
    </div>
</template>
<script>
import {cloneDeep} from 'lodash';
import tableRoleList from './table-role-list.vue';
import tableRolegpList from './table-rolegp-list.vue';
import tableUserList from './table-user-list.vue';

export default {
    components: {tableRoleList, tableRolegpList, tableUserList},
    data() {
        return {
            columns: [
                {type: 'selection', minWidth: 60, align: 'center', show: true},
                {title: '用户名', key: 'userName', minWidth: 140, show: true},
                {title: '登录账号', key: 'account', minWidth: 120, show: true},
                {title: '手机号', key: 'mobilePhone', minWidth: 140, show: true},
                {title: '邮箱', key: 'email', minWidth: 200, show: true},
                {title: '性别', key: 'genderCode', slot: 'gender', minWidth: 100, show: true},
                {title: '状态', key: 'useStateCode', slot: 'status', minWidth: 100, show: true},
                {title: '所属职位', key: 'positionId', slot: 'position', minWidth: 100, show: false},
                {title: '所属部门', key: 'deptId', slot: 'dept', minWidth: 100, show: false},
                {title: '创建时间', key: 'createTime', minWidth: 200, show: false},
                {title: '用户 ID', key: 'id', minWidth: 120, show: false},
                {title: '操作', key: 'action', slot: 'action', minWidth: 200, align: 'center', fixed: 'right', show: true}
            ],
            loading: false,
            list: [],
            selectedData: [],
            sortType: 'normal', // 当前排序类型，可选值为：normal（默认） || asc（升序）|| desc（降序）,
            sortKey: '', // 排序列的 key
            tableSize: 'default',
            tableFullscreen: false,
            userInfo: null, // 当前选中的用户信息
            userInfoString: '', // 当前选中的用户信息字符串
            userInfoRules: {
                userName: [
                    {required: true, message: '请输入用户名', trigger: 'blur'}
                ],
                mobilePhone: [
                    {required: true, message: '请输入手机号', trigger: 'blur'},
                    {pattern: /^1[3456789]\d{9}$/, message: "手机号码格式不正确", trigger: "blur"}
                ],
                email: [
                    /* {required: true, message: '请输入邮箱', trigger: 'blur'}, */
                    {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
                ],
                account: [
                    {required: true, message: '请输入登录账号', trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入登录密码', trigger: 'blur'},
                    {type: 'string', min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
                ],
            },
            userInfoFormReady: true,
            drawer: {
                show: false,
                type: 'edit', // edit || read || new
                styles: {
                    height: 'calc(100% - 55px)',
                    overflow: 'auto',
                    paddingBottom: '53px',
                    position: 'static'
                }
            },
            submitting: false,
            modal: {
                show: false
            },
            pageSizeOpts: [10, 30, 50, 100],
            pageNation: {total: 0, pageSize: 10, pageNumber: 1},
            modalTop: 200,
            modalHeight: 0,
            userInfoParam: {},
            selectedRoleIds: [],
            selectedRolegpIds: [],
            userModalShow: false,
            userAccountObject: null,
            accountRoleObject: null,
        }
    },
    computed: {
        // 动态设置列
        tableColumns() {
            const columns = [...this.columns];
            return columns.filter(item => item.show);
        },
        lang () {
            return {
                'en-US': {
                    cancel: 'cancel',
                    confirmDelete: 'confirm delete?',
                    resetPassword: 'reset Password',
                    confirm: 'confirm'
                },
                'zh-CN': {
                    cancel: '取消',
                    confirmDelete: '确认删除？',
                    resetPassword: '重置密码',
                    confirm: '确认'
                }
            }[this.G_Locale]
        }
    },
    methods: {
        handleUserSelect() {
            this.$refs.tableUser.getData();
            this.userModalShow = true;
        },
        onInputClear() {
            this.userInfo.link = '';
        },
        handleSelectSubmit(user) {
            console.log(user);
            this.userInfo.userName = user.peopleName;
            this.userInfo.userId = user.id;
            this.userInfo.mobilePhone = user.phoneNumber;
            this.userInfo.genderCode = user.gender == "女" ? '2' :"1";
            //this.userInfo.link = user.id;
            this.userModalShow = false;
        },
        handleUserModalClose() {
            this.userModalShow = false;
        },
        //窗体监听方法
        initElementHeight() {
            //然后监听window的resize事件
            const _this = this;
            _this.calcElementHeight(_this);
            window.onresize = function temp() {
                _this.calcElementHeight(_this);
            };
        },
        calcElementHeight(_this) {
            _this.$nextTick(() => {
                this.modalHeight = document.documentElement.clientHeight - this.modalTop * 2 - 80;
            });
        },
        getData() {
            if (this.loading) return;
            this.loading = true;
            // 下面的 params 是获取的表单查询参数
            this.list = [];
            this.pageNation.total = 0;
            let condition = "";
            const params = this.$parent.$parent.$refs.form.data;
            if (params.userName != null && params.userName != "") {
                condition += "userName like '" + params.userName + "'";
            }
            if (params.mobilePhone != null && params.mobilePhone != "") {
                condition += "mobilePhone like '" + params.mobilePhone + "'";
            }
            if (params.email != null && params.email != "") {
                condition += "email like '" + params.email + "'";
            }
            if (params.genderCode != null && params.genderCode != "") {
                condition += "genderCode like '" + params.genderCode + "'";
            }
            if (params.account != null && params.account != "") {
                condition += "account like '" + params.account + "'";
            }
            if (params.useStateCode != null && params.useStateCode != "") {
                condition += "useStateCode like '" + params.useStateCode + "'";
            }
            if (params.id != null && params.id != "") {
                condition += "id like '" + params.id + "'";
            }
            this.$api.AccountUser.queryByPage(this.pageNation.pageNumber, this.pageNation.pageSize, {condition}).then(res => {
                this.list = cloneDeep(res.records);
                this.pageNation.total = res.recordCount;
                this.pageNation.pageNumber = res.pageNumber;
                this.pageNation.pageSize = res.pageSize;
            }).finally(() => {
                this.loading = false;
            });
        },
        // 改变表格尺寸
        handleChangeTableSize(size) {
            this.tableSize = size;
        },
        // 表格全屏
        handleFullscreen() {
            this.tableFullscreen = !this.tableFullscreen;
            this.$emit('on-fullscreen', this.tableFullscreen);
        },
        // 刷新表格数据
        handleRefresh() {
            this.getData();
        },
        // 切换页码
        handleChangePage(page) {
            this.pageNation.pageNumber = page;
            this.getData();
        },
        // 切换每页条数
        handleChangePageSize(size) {
            this.pageNation.pageNumber = 1;
            this.pageNation.pageSize = size;
            this.getData();
        },
        // 排序
        handleSortChange({key, order}) {
            this.pageNation.pageNumber = 1;
            this.sortType = order;
            this.sortKey = key;
            this.getData();
        },
        // 选中一项，将数据添加至已选项中
        handleSelect(selection, row) {
            this.selectedData.push(row);
        },
        // 取消选中一项，将取消的数据从已选项中删除
        handleSelectCancel(selection, row) {
            const index = this.selectedData.findIndex(item => item.id === row.id);
            this.selectedData.splice(index, 1);
        },
        // 当前页全选时，判断已选数据是否存在，不存在则添加
        handleSelectAll(selection) {
            selection.forEach(item => {
                if (this.selectedData.findIndex(i => i.id === item.id) < 0) {
                    this.selectedData.push(item);
                }
            });
        },
        // 清空所有已选项
        handleClearSelect() {
            this.selectedData = [];
        },
        // 查找单一用户信息
        handleGetUser(id) {
            return this.list.find(item => item.id === id);
        },
        // 删除
        handleDelete(id) {
            if (this.loading) return;
            let _this = this;
            this.$Modal.confirm({
                title: this.lang['confirmDelete'],
                cancelText: this.lang['cancel'],
                content: `您确认要删除用户<strong>${this.handleGetUser(id).userName}</strong>？`,
                onOk () {
                    _this.deleteUser(id);
                }
            })
        },
        //根据职位ID删除职位
        deleteUser(id) {
            this.$api.AccountUser.deleteById(id).then(res => {
                this.submitting = false;
                this.drawer.show = false;
                this.$Modal.remove();
                this.handleClearSelect();
                this.handleChangePage(1);
            })
        },
        // 批量删除
        handleDeleteMultiple() {
            if (this.loading) return;
            const ids = this.selectedData.map(item => item.id);
            const names = this.selectedData.map(item => item.userName);
            let _this = this;
            this.$Modal.confirm({
                title: this.lang['confirmDelete'],
                cancelText: this.lang['cancel'],
                content: `您确认要删除用户<strong>${names}</strong>？`,
                onOk () {
                    _this.deletePositionMultiple(ids);
                }
            })
        },
        //批量删除
        deletePositionMultiple(ids) {
            this.$api.AccountUser.deleteByIds(ids).then(res => {
                this.submitting = false;
                this.drawer.show = false;
                this.$Modal.remove();
                this.handleClearSelect();
                this.handleChangePage(1);
            })
        },
        // 编辑
        handleEdit(id) {
            this.userInfo = cloneDeep(this.handleGetUser(id));
            this.userInfo.password = '';
            this.userInfoString = JSON.stringify(this.userInfo);
            this.drawer.type = 'edit';
            this.drawer.show = true;
            this.handleInitUserInfoForm();
        },
        // 关闭编辑
        handleCloseEdit() {
            // 判断内容是否修改，没修改则直接关闭
            if (this.drawer.type === 'edit') {
                const editUserInfo = cloneDeep(this.userInfo);
                const editUserInfoString = JSON.stringify(editUserInfo);
                if (editUserInfoString !== this.userInfoString) {
                    return new Promise((resolve) => {
                        this.$Modal.confirm({
                            title: this.lang['confirm'],
                            cancelText: this.lang['cancel'],
                            content: '您已经修改了用户信息，是否直接关闭？',
                            onOk: () => {
                                resolve();
                            }
                        });
                    });
                }
            }
        },
        // 用户详情
        handleClickRow(row) {
            this.userInfo = cloneDeep(this.handleGetUser(row.id));
            this.drawer.type = 'read';
            this.drawer.show = true;
            this.handleInitUserInfoForm();
        },
        // 添加用户
        handleOpenCreate() {
            
            this.userInfo = {
                id: '',
                userName: '',
                account: '',
                password: '',
                mobilePhone: '',
                email: '',
                genderCode: 1,
                useStateCode: 1,
                userDescrib: ''
            };
            this.drawer.type = 'new';
            this.drawer.show = true;
            this.handleInitUserInfoForm();
        },
        handleSubmitEdit() {
            
            this.$refs.userInfoForm.validate(valid => {
                if (valid) {
                    if (this.submitting) return;
                    this.submitting = true;
                    this.userInfo.password = this.tools.md5(this.userInfo.password);
                    this.$api.AccountUser.update(this.userInfo).then(res => {
                        this.submitting = false;
                        this.drawer.show = false;
                        this.handleClearSelect();
                        this.handleChangePage(1);
                    });
                }
            });
        },
        handleSubmitNew() {
            this.$refs.userInfoForm.validate(valid => {
                if (valid) {
                    if (this.submitting) return;
                    this.submitting = true;
                    this.userInfo.password = this.tools.md5(this.$api.AccountUser.getDefaultPassword() + this.$api.AccountUser.getSlat());
                    this.$api.AccountUser.add(this.userInfo).then(res => {
                        this.submitting = false;
                        this.drawer.show = false;
                        this.handleClearSelect();
                        this.handleChangePage(1);
                    })
                }
            });
        },
        handleInitUserInfoForm() {
            this.userInfoFormReady = false;
            this.$nextTick(() => {
                this.userInfoFormReady = true;
            });
        },
        // 打开分配权限
        handleOpenPermission(id) {
            this.userInfo = cloneDeep(this.handleGetUser(id));
            this.userInfoString = JSON.stringify(this.userInfo);
            this.selectedRoleIds = [];
            this.selectedRolegpIds = [];
            let condition = "accountId=" + this.userInfo.id;
            this.$api.AccountRole.query({condition}).then(records => {
                if (records && records.length > 0) {
                    records.map(r => {
                        if (r.roleId == null) {
                            this.selectedRolegpIds.push(r.rolegpId)
                        } else {
                            this.selectedRoleIds.push(r.roleId)
                        }
                    })
                }
                this.$refs.tableRole.selectedRoleData = [];
                this.$refs.tableRolegp.selectedRolegpData = [];
                this.$refs.tableRole.pageNation.pageNumber = 1;
                this.$refs.tableRole.getData();
                this.$refs.tableRolegp.pageNation.pageNumber = 1;
                this.$refs.tableRolegp.getData();
                this.modal.show = false;
                this.roleRefresh = false
                this.$nextTick(() => {
                    this.modal.show = true;
                })
            })
        },
        handleSubmitPermission() {
            let roleIds = this.$refs.tableRole.selectedRoleData;
            let rolegpIds = this.$refs.tableRolegp.selectedRolegpData;
            let condition = "accountId=" + this.userInfo.id;
            let records = [];
            roleIds.map(roleId => {
                records.push({accountId: this.userInfo.id, roleId: roleId})
            })
            rolegpIds.map(rolegpId => {
                records.push({accountId: this.userInfo.id, rolegpId: rolegpId})
            })

            if (this.submitting) return;
            this.submitting = true;
            this.$api.AccountRole.firstDeleteAndAdd(condition, records).then(res => {
                this.submitting = false;
                this.modal.show = false;
            })
        },
        handleResetPassword() {
            let _this = this;
            this.$Modal.confirm({
                title: this.lang['resetPassword'],
                cancelText: this.lang['cancel'],
                onOk () {
                    _this.resetPassword();
                }
            })
        },
        resetPassword() {
            this.userInfo.password =  this.tools.md5(this.$api.AccountUser.getDefaultPassword() + this.$api.AccountUser.getSlat());
            this.$api.AccountUser.update(this.userInfo).then((res) => {
                this.userInfoString = JSON.stringify(this.userInfo);
                this.$Modal.remove();
            })
        }
    },
    mounted() {
        this.initElementHeight();
    }
}
</script>
<style lang="less">
.page-sys-user {
    &-drawer {
        &-footer {
            width: 100%;
            position: absolute;
            bottom: 0;
            left: 0;
            border-top: 1px solid #e8e8e8;
            padding: 10px 16px;
            text-align: right;
            background: #fff;
        }

        &-form {
            .ivu-input[disabled], fieldset[disabled] .ivu-input, .ivu-select-disabled .ivu-select-selection {
                background-color: #fff;
                color: inherit;
            }

            &-region {
                .i-region-transfer {
                    width: 270px;
                }

                .i-region-drop-main {
                    width: 270px !important;
                    height: 200px;
                    overflow: auto;
                    column-count: 2;

                    &-item {
                        line-height: normal;
                    }
                }
            }
        }
    }
}
</style>
